package com.lzp.java.concurrent.threadlocal;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 多个线程同时执行打印时间任务，共用一个SimpleDateFormat对象时，会存在线程安全问题
 * <p>
 * 加锁的方法可以解决线程安全问题
 *
 * @author lzp
 * @date 2020/03/29
 */
public class WrongWaySimpleDateFormater2 {

    public static ExecutorService threadPool = Executors.newFixedThreadPool(10);
    static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 1000; i++) {
            int finalI = i;
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    String date = new WrongWaySimpleDateFormater2().dateThreadSafe(finalI);
                    System.out.println(date);
                }
            });
        }
        threadPool.shutdown();
    }

    /**
     * 线程不安全的实现
     *
     * @param seconds
     * @return
     */
    public String date(int seconds) {
        //参数的单位是毫秒，从1970.1.1 00:00:00 GMT计时
        Date date = new Date(1000 * seconds);
        return dateFormat.format(date);
    }

    /**
     * 加锁实现线程安全
     *
     * @param seconds
     * @return
     */
    public String dateThreadSafe(int seconds) {
        //参数的单位是毫秒，从1970.1.1 00:00:00 GMT计时
        Date date = new Date(1000 * seconds);
        String result = null;
        synchronized (WrongWaySimpleDateFormater2.class) {
            result = dateFormat.format(date);
        }
        return result;
    }
}